package practice3.persistence.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;

import practice3.persistence.User;


public class MyDaoImpl extends BaseDao implements MyDao {

	@Override
	public List<User> doQuery() throws Exception {
		return getJdbcTemplate().query("SELECT * FROM USERS", new UserRowMaper());
	}
	
	private static class UserRowMaper implements RowMapper {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getString("ID"));
			user.setName(rs.getString("NAME"));
			return user;
		}
	}
	
	public void addUser(User u) throws Exception {
		String sql = "insert into users(id,name) values(?,?)";
		getJdbcTemplate().update(sql, new Object[]{u.getId(),u.getName()});
	}
	
	
	/**
	 * <p>Method ：addUserEx
	 * <p>Description : 插入两条主键相同的记录，诱发数据库异常
	 *
	 * @param u
	 * @throws Exception 
	 * @see practice3.persistence.dao.MyDao#addUserEx(practice3.persistence.User)
	 */
	public void addUserEx(User u) throws Exception {
		String sql = "insert into users(id,name) values(?,?)";
		getJdbcTemplate().update(sql, new Object[]{u.getId(),u.getName()});
		getJdbcTemplate().update(sql, new Object[]{u.getId(),u.getName()});//引发数据库主键冲突异常
	}

	/**
	 * <p>Method ：getUserById
	 * <p>Description : 功能描述
	 *
	 * @param id
	 * @throws Exception 
	 * @see practice3.persistence.dao.MyDao#getUserById(java.lang.String)
	 */
	@Override
	public User getUserById(String id) throws Exception {
		return (User) getJdbcTemplate().query("SELECT * FROM USERS where id = '"+id+"'", new UserRowMaper()).get(0);
	}
}
